import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.junit.Before;
import org.junit.Test;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Map;

public class _5查询全部QueryBuilders_matchAllQuery方法搜索 {

    //定义全局变量
    private PreBuiltTransportClient transportClient;


    /*配置初始化*/
    @Before
    public void Before() throws UnknownHostException {

        //1.创建一个settings对象,xiang相当于是一个配置信息,主要配置集群的名字
        //Settings settings= Settings.builder().put("cluster.name","cluster-es").build();
        Settings settings = Settings.EMPTY;// 这个是单节点创建,等同于上面的的代码创建
        //2.创建一个客户端对象
        transportClient = new PreBuiltTransportClient(settings);
        //3.设置集群的信息(java和es引擎端口之间的连接是9300)
        transportClient.addTransportAddresses(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9300));

    }

    /*搜索*/
    @Test
    public void searchMain() {
        //1. 设置查询的条件(查询全部  QueryBuilders.matchAllQuery())
        QueryBuilder queryBuilder = QueryBuilders.matchAllQuery();

        /*这里可以设置跨库和跨表的搜索,*/
        // transportClient.prepareSearch("library1","library2","library3",...); 跨库搜索
        // transportClient.prepareSearch("library1").setTypes("table1","table2",...)// 在一个库中跨表搜索
        // transportClient.prepareSearch("library1","library2",...).setTypes("table1","table2",...)// 跨库跨表搜索

        //2.设置在一个库中搜索条件类型
        SearchResponse response = transportClient.prepareSearch("blog1").setTypes("content").setQuery(queryBuilder).get();

        //3.获取查询结果
        SearchHits searchHits = response.getHits();
        System.out.println("一共找到( "+searchHits.totalHits+" )条数据");

        //4.遍历查询的数据
        for (SearchHit searchHit : searchHits) {
            System.out.println(searchHit.getSourceAsString());

            Map<String, Object> map = searchHit.getSourceAsMap();
            System.out.println(map.get("id"));
            System.out.println(map.get("title"));
            System.out.println(map.get("content"));
        }


        //关闭资源
        transportClient.close();

    }


}



